package eu.webhib.webblog.application;

import eu.webhib.frmwrk.jsf.utils.MsgUtil;
import eu.webhib.frmwrk.utils.*;

import eu.webhib.webblog.domain.User;

//
public class ApplMail {
   //
   public static final String emailConfirmUrlParam = "ID";

   private static String baseUrl = null;

   public static void setup(String baseUrl) {
         ApplMail.baseUrl = baseUrl;
   }

   public static boolean sendUserMail(String emailAddress, String mailTextKey, String mailSubjectKey, String confirmPage, User user) {

      String mailContent = MsgUtil.getMessageText(mailTextKey);
      if (confirmPage != null) {
         mailContent = mailContent.replaceFirst("\\{CONFIRMATION_LINK\\}", createConfirmLink(confirmPage, user));
      }
      mailContent = mailContent.replaceAll("\\{WEB_SITE_NAME\\}", ApplProperties.get("web.siteName")).
              replaceAll("\\{USER_NAME\\}", user.getUserName());

      boolean ret = MailUtils.sendMail(emailAddress,
              MsgUtil.getMessageText(mailSubjectKey),
              mailContent);
      if (ApplProperties.getBoolean("mail.debug", false)) {
         MailUtils.receiveMails();
      }
      return ret;
   }

   private static String createConfirmLink(String confirmPage, User user) {
      assert (user.getConfirmSecret() != null);
      return baseUrl + confirmPage + "?"
              + emailConfirmUrlParam + "=" + user.getConfirmSecret();
   }

   // todo: currently not needed
   private String connectTextKeys(String textKey) {
      StringBuilder mailContentBuilder = new StringBuilder();
      for (int i = 1; true; i++) {
         String msg = MsgUtil.getMessageTextIfExists(textKey + i);
         if (msg == null) {
            break;
         }
         mailContentBuilder.append(msg);
         mailContentBuilder.append(ApplConsts.LINE_SEPARATOR);
      }
      return mailContentBuilder.toString();
   }
}
